//
//  DocumentView.swift
//  Chatup
//
//  Created by iron man on 2024/1/15.
//

import SwiftUI
import UniformTypeIdentifiers


struct DocumentView: View {
    @Environment(\.presentationMode) var presentationMode
    @State private var imaginationText: String = ""
    @State private var fileName: String = ""
    @State private var fileUrl: URL?
    @State private var hasFile: Bool = false
    @State private var showFiles: Bool = false
    @State private var fileOverSize: Bool = false
    @State private var showAlert: Bool = false
    @State var showVIP = false
    @State var isVip = UserDefaults.standard.bool(forKey: "kWhetherVip")
    @State private var isLoading = false
    var body: some View {
        GeometryReader { geometry in
            ZStack{
                VStack (alignment: .center){
                    Spacer().frame(height: 16)
                    HStack {
                        Button {
                            if isLoading{return}
                            presentationMode.wrappedValue.dismiss()
                        } label: {
                            Image("nav_close")
                                .resizable()
                                .frame(width: 12, height: 12)
                        }
                        Spacer()
           
                        if !isVip{
                            Button {
                                showVIP.toggle()
                            } label: {
                                Image("icon_setting_vip_right")
                                    .resizable()
                                    .frame(width: 77, height: 24)
                            }
                        }
                        

                    }.padding(.horizontal, 22)
                        
                    Spacer().frame(height: 16)
                        
                    Text("📄" + String.i18nText("feature_summarize_document"))
                        .font(.system(size: 28).weight(.bold))
                        .foregroundColor(.white)
                    Text(String.i18nText("feature_summarize_document_hint1"))
                        .font(.system(size: 16))
                        .foregroundColor(Color(red: 0.51, green: 0.51, blue: 0.51))
                        .frame(width: 316, height: 71, alignment: .topLeading)
                        
                    Spacer().frame(height: 16)
                    HStack (alignment: .center){
                        Spacer().frame(width: 22)
                        Button {
                            if(!hasFile){
                                showFiles.toggle()
                            }
                        } label: {
                            if(hasFile){
                                ZStack(alignment: .topTrailing){
                                    Image("ic_file_media")
                                        .resizable()
                                        .frame(width: 30, height: 30)
                                        .foregroundColor(.clear)
                                        .frame(width: 68, height: 68)
                                        .background(Color(red: 0.13, green: 0.13, blue: 0.14))
                                        .cornerRadius(10)
                                    Image("ic_delete")
                                      .resizable()
                                      .aspectRatio(contentMode: .fill)
                                      .frame(width: 27, height: 27)
                                      .clipped()
                                      .onTapGesture {
                                          hasFile = false
                                          fileUrl = nil
                                          fileName =  ""
                                      }
                                }.frame(width: 68, height: 68)
                            }else{
                                Image("ic_add_media")
                                    .resizable()
                                    .frame(width: 30, height: 30)
                                    .foregroundColor(.clear)
                                    .frame(width: 68, height: 68)
                                    .background(Color(red: 0.13, green: 0.13, blue: 0.14))
                                    .cornerRadius(10)
                            }
                        }.fileImporter(isPresented: $showFiles, allowedContentTypes: [
                            UTType(filenameExtension: "txt") ?? .plainText,
                            UTType(filenameExtension: "pdf") ?? .pdf,
                            UTType(filenameExtension: "docx") ?? .data
                        ], allowsMultipleSelection: false, onCompletion: { result in
                            do {
                                guard let selectedFile: URL = try result.get().first else { return }
                                
                                let hasAccess = selectedFile.startAccessingSecurityScopedResource()
                                 
                                if hasAccess{
                                    let maxSizeInBytes = 2 * 1024 * 1024
                                    // 检查文件大小
                                    let attributes = try FileManager.default.attributesOfItem(atPath: selectedFile.path)
                                    if let fileSize = attributes[.size] as? Int64, fileSize <= maxSizeInBytes {
                                        hasFile = true
                                        fileUrl = selectedFile
                                        fileName = selectedFile.path.components(separatedBy: "/").last ?? "未知"
                                        fileOverSize = false
                                    } else {
                                        hasFile = false
                                        fileUrl = nil
                                        fileName =  ""
                                        fileOverSize = true
                                        showAlert = true
                                    }
                                }else{
                                    print("无法访问文件")
                                    hasFile = false
                                    fileUrl = nil
                                    fileName =  ""
                                }
                            } catch {
                                hasFile = false
                                fileUrl = nil
                                fileName =  ""
                            }
                        }).alert(isPresented: $showAlert) {
                            // 创建Alert实例
                            Alert(
                                title: Text(""),
                                message: Text(String.i18nText("feature_summarize_document_toast")),
                                dismissButton: .default(Text(String.i18nText("continue"))) {
                                    // 点击好的按钮后的操作
                                    
                                }
                            )
                        }
                        
                        if hasFile {
                            Spacer().frame(width: 20)
                            Text(fileName)
                                .font(.system(size: 16))
                                .foregroundColor(.white)
                        } else {
                            Spacer().frame(width: 20)
                            VStack(alignment: .leading) {
                                Text(String.i18nText("feature_summarize_document_size"))
                                    .font(.system(size: 16))
                                    .foregroundColor(.white)
                                Text(String.i18nText("feature_summarize_document_format"))
                                    .font(.system(size: 16))
                                    .foregroundColor(Color(red: 0.15, green: 0.75, blue: 0.46))
                            }
                        }
                        Spacer()
                    }
                    Spacer().frame(height: 26)
                    // 文本输入
                        
                    TextView(hint: String.i18nText("feature_recognize_images_hint2"), text: $imaginationText).padding(.horizontal,23)
                        
                    Spacer()

                    // 'Draw' 按钮
                    Button(action: {
                        if fileOverSize {
                            showAlert = true
                            return
                        }
                        isVip = UserDefaults.standard.bool(forKey: "kWhetherVip")
                        if !isVip {
                            showVIP.toggle()
                            return
                        }
                        if(!hasFile && imaginationText.count == 0 && fileUrl == nil) {
                            return
                        }
                        
                        let fileModel = MsgModel(type: .user, messageType: .file, message: fileName, roleId: 0, isLike: false, isUnlike: false)
                        let msgModel  = MsgModel(type: .user, messageType: .text, message: imaginationText, roleId: 0, isLike: false, isUnlike: false)
                        
                        let msg1Model  = MsgModel(type: .bot, messageType: .text, message: "", roleId: 0, isLike: false, isUnlike: false, context: imaginationText + "#" + fileUrl!.absoluteString)
                        
                        DispatchQueue.main.async {
                            NotificationCenter.default.post(name: Notification.Name("kAppendMessage"), object: ["feature":FeaturesType.document,"msgs":[fileModel, msgModel, msg1Model]])
                            
                            presentationMode.wrappedValue.dismiss()
                        }
                        
  
                        
                    }) {
                        Text(String.i18nText("feature_summarize"))
                            .font(.system(size: 18).weight(.bold))
                            .foregroundColor(Color(red: 1, green: 1, blue: 1))
                            .foregroundColor(.clear)
                            .frame(minWidth: 0, maxWidth: .infinity)
                            .frame(height: 57)
                            .background(
                                imaginationText.isEmpty ? Color(red: 0.54, green: 0.54, blue: 0.55) :
                                    Color(red: 0.15, green: 0.75, blue: 0.46)
                            )
                            .cornerRadius(12)
                    }
                    .padding()

                    Spacer().frame(height: 32)
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .background(Color.black.opacity(0.8))
                .edgesIgnoringSafeArea(.all)
                .fullScreenCover(isPresented: $showVIP, content: {
                    VipView(viewModel: .init(from: "feature_summarize_document"))
                })
                .onReceive(NotificationCenter.default.publisher(for: Notification.Name("refreshVip"))) { _ in
                    isVip = UserDefaults.standard.bool(forKey: "kWhetherVip")
                }
                .onTapGesture {
                    NotificationCenter.default.post(name: Notification.Name("kChangeFocused"), object: nil)
                }.alert(isPresented: $showAlert) {
                    // 创建Alert实例
                    Alert(
                        title: Text(""),
                        message: Text(String.i18nText("feature_summarize_document_toast")),
                        dismissButton: .default(Text(String.i18nText("continue"))) {
                            // 点击好的按钮后的操作
                            
                        }
                    )
                }
                if isLoading{
                    ProgressView()
                        .progressViewStyle(CircularProgressViewStyle(tint: .white))
                        .scaleEffect(2)
                }
            }
        }
    }
}

